<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body center @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上架名称" prop="projectName">
          <el-input v-model="form.projectName" size="small" placeholder="请输入上架名称"/>
        </el-form-item>
        <el-form-item label="上架上限" prop="pulishUpperLimit">
          <el-input v-model="form.pulishUpperLimit" disabled type="number" size="small"
                    placeholder="请输入每天上架并选择计划执行日期"/>
        </el-form-item>
        <el-form-item label="每天上架" prop="pulishNumberByDay">
          <el-input v-model="form.pulishNumberByDay" type="number" size="small" placeholder="请输入每天上架数量"/>
        </el-form-item>
        <el-form-item label="计划执行日期" prop="pulishBeginTime">
          <el-date-picker @change="chooseGroundDate" type="daterange" v-model="groundDate" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" placeholder="选择日期范围"
                          value-format="yyyy-MM-dd" format="yyyy-MM-dd" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上架时间" prop="pulishBeginTime">
          <el-time-picker @change="chooseGroundTime" is-range v-model="groundTime" range-separator="—"
                          start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"
                          value-format="HH:mm" format="HH:mm"
                          :picker-options="{selectableRange:'01:00-23:59',minTime:'01:00'}">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="价格区间" prop="priceCeiling">
          <el-input @input="changeProductNumber" v-model="form.priceFloor" type="number" size="small"
                    style="width: 150px"
                    placeholder="最低价"/>
          —
          <el-input @input="changeProductNumber" v-model="form.priceCeiling" type="number" style="width: 150px"
                    size="small" placeholder="最高价"/>
        </el-form-item>
        <el-form-item label="商品品牌" :prop="form.isBrand=='1'?'productBrand':'isBrand'">
          <el-radio-group @change="changeProductNumber" v-model="form.isBrand">
            <el-radio label="0">无品牌</el-radio>
            <el-radio label="1">有品牌</el-radio>
          </el-radio-group>
          <el-select class="ml5" @change="changeProductNumber" v-if="form.isBrand=='1'" v-model="form.productBrand"
                     placeholder="请选择品牌"
                     filterable clearable multiple size="small">
            <el-option v-for="dict in brandList" :key="dict.value" :label="dict.brandName" :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="选品范围" prop="productWarehouse">
          <el-radio-group @change="changeProductNumber" v-model="form.productWarehouse">
            <el-radio label="0">公共产品库</el-radio>
            <el-radio label="1">2.0产品库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.productWarehouse=='0'" label="选品类型" prop="productTemplateType">
          <el-select @change="changeProductNumber" class="ml5" v-model="form.productTemplateType"
                     placeholder="请选择商品类型" clearable size="small">
            <el-option v-for="dict in dict.type.select_product_range" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类目" prop="productCategory">
          <div>
            <el-select class="ml5" v-model="categoryValueData.category0" placeholder="请选择一级类目" clearable
                       size="small" filterable @change="getSubcategoryList(categoryValueData.category0,'0')">
              <el-option v-for="dict in categoryList" :key="dict.id" :label="dict.name"
                         :value="dict.id"/>
            </el-select>
            <span class="ml10">商品数量：{{ categoryValueData.number0 }}</span>
          </div>
          <div v-if="categoryValueData.list0 && categoryValueData.list0.length>0">
            <el-select class="ml5" v-model="categoryValueData.category1" placeholder="请选择二级类目"
                       clearable
                       size="small" filterable @change="getSubcategoryList(categoryValueData.category1,'1')">
              <el-option v-for="dict in categoryValueData.list0" :key="dict.id" :label="dict.name"
                         :value="dict.id"/>
            </el-select>
            <span class="ml10">商品数量：{{ categoryValueData.number1 }}</span>
          </div>
          <div v-if="categoryValueData.list1 && categoryValueData.list1.length>0">
            <el-select class="ml5" v-model="categoryValueData.category2" placeholder="请选择三级类目"
                       clearable filterable size="small" @change="getSubcategoryList(categoryValueData.category2,'2')">
              <el-option v-for="dict in categoryValueData.list1" :key="dict.id" :label="dict.name"
                         :value="dict.id"/>
            </el-select>
            <span class="ml10">商品数量：{{ categoryValueData.number2 }}</span>
          </div>
          <div v-if="categoryValueData.list2 && categoryValueData.list2.length>0">
            <el-select class="ml5" v-model="categoryValueData.category3" placeholder="请选择四级类目"
                       clearable filterable size="small"
                       @change="getCategoryProductNumber(categoryValueData.category3,'3')">
              <el-option v-for="dict in categoryValueData.list2" :key="dict.id" :label="dict.name"
                         :value="dict.id"/>
            </el-select>
            <span class="ml10">商品数量：{{ categoryValueData.number3 }}</span>
          </div>
        </el-form-item>
        <el-form-item label="定价模板" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择定价模板" clearable size="small">
            <el-option v-for="dict in priceTemplateList" :key="dict.value" :label="dict.lable" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="联盟折扣" :prop="form.isAfflicateDiscount== '1'?'afflicateDiscount':'isAfflicateDiscount'">
          <el-radio-group v-model="form.isAfflicateDiscount" @input="changeAfflicateDiscount">
            <el-radio label="0">默认定价模板</el-radio>
            <el-radio label="1">自定义</el-radio>
          </el-radio-group>
          <el-input v-if="form.isAfflicateDiscount== '1'" type="number" class="ml10" style="width: 150px"
                    v-model="form.afflicateDiscount" size="small" placeholder="请输入">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="单品折扣" :prop="form.isProductDiscount== '1'?'productDiscount':'isProductDiscount'">
          <el-radio-group v-model="form.isProductDiscount" @input="changeProductDiscount">
            <el-radio label="0">默认定价模板</el-radio>
            <el-radio label="1">自定义折扣名称</el-radio>
          </el-radio-group>
          <el-input v-if="form.isProductDiscount== '1'" class="ml10" style="width: 150px"
                    v-model="form.productDiscount" size="small" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="商品分组" :prop="form.isProductGroup== '1'?'productGroup':'isProductGroup'">
          <el-radio-group v-model="form.isProductGroup" @input="changeProductGroup">
            <el-radio label="0">默认为第三级类目名称</el-radio>
            <el-radio label="1">自定义</el-radio>
          </el-radio-group>
          <el-input v-if="form.isProductGroup== '1'" class="ml10" style="width: 150px" v-model="form.productGroup"
                    size="small" placeholder="请输入">
          </el-input>
        </el-form-item>
        <!--        <el-form-item label="审核商品" prop="reviewStatus">-->
        <!--          <el-radio-group v-model="form.reviewStatus">-->
        <!--            <el-radio label="0">不处理</el-radio>-->
        <!--            <el-radio label="1">自动下架</el-radio>-->
        <!--            <el-radio label="2">下架并删除</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getBrandListByStoreId} from "@/api/gather/collectProduct";
import {
  addPulishProductProject,
  editPulishProject,
  queryProjectById, queryStoreProductNumber
} from "@/api/autoOperation/ground";
import {
  selectListBySellerId,
  querySubCategoryListByStoreId,
  querySubordinateCategory
} from "@/api/autoOperation"

export default {
  name: "grounding",
  dicts: ['select_product_range'],
  props: {
    storeId: {
      type: String,
      default: ''
    },
    configId: { //配置id
      type: String,
      default: ""
    },
    userId: { // 绑定店铺的用户id
      type: String,
      default: ""
    },
    storeUserName: { //店铺账号 cn码
      type: String,
      default: ""
    },
    isUseShareCode: { // 是否使用分享码
      type: String,
      default: "0"
    },
  },
  data() {
    return {
      buttonLoading: false, //确定提交表单按钮loading
      title: "新增上架配置",
      open: true,
      form: {},
      brandList: [], //品牌列表
      categoryList: [], //商品类目列表
      secondCategoryList: [],//二级类目列表
      tertiaryCategoryList: [],//三级类目列表
      fourthCategoryList: [],//四级类目列表
      categoryIndex: 0,//选择类目的下标
      categoryValueData: {
        category0: '',
        category1: '',
        category2: '',
        category3: '',
        number0: '',
        number1: '',
        number2: '',
        number3: '',
        list0: [],
        list1: [],
        list2: [],
        // list3: [],
      },
      priceTemplateList: [], //智能定价模板列表
      isCustomProductDiscount: '0', //是否自定义单品折扣
      isCustomProductGroup: '0', //是否自定义商品分组
      groundTime: ["01:00", "23:59"], //上架时间
      groundDate: [this.parseTime(new Date().getTime(), '{y}-{m}-{d}'), this.parseTime(new Date().getTime(), '{y}-{m}-{d}')],//计划执行日期
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() + 24 * 60 * 60 * 1000 < new Date().getTime();
        },
      },
      rules: {
        projectName: [{required: true, message: "上架名称不能为空", trigger: "blur"}],
        pulishNumberByDay: [
          {required: true, trigger: "blur", message: "每天上架数量不能为空"},
          {required: true, trigger: "change", validator: this.checkGroundNum}],
        pulishUpperLimit: [{required: true, trigger: "blur", message: "上架上限不能为空！"},
          {required: true, trigger: "blur", validator: this.checkGroundLimit}],
        priceFloor: [{required: false, trigger: "change"}],
        priceCeiling: [{required: false, trigger: "blur", message: "价格区间不能为空"},
          {required: false, trigger: "blur", validator: this.multipllCheck}],
        pulishBeginTime: [{required: true, message: "请选择上架时间", trigger: "change"}],
        productBrand: [{required: true, message: "请选择商品品牌", trigger: "change"}],
        isBrand: [{required: true, message: "请选择商品品牌", trigger: "change"}],
        afflicateDiscount: [
          {required: true, message: "联盟折扣不能为空", trigger: "blur"},
          {required: true, trigger: "blur", validator: this.$Validate.isPositiveInteger}],
        isAfflicateDiscount: [{required: true, message: "联盟折扣不能为空", trigger: "blur"}],
        productDiscount: [{required: true, message: "单品折扣不能为空", trigger: "blur"}],
        isProductDiscount: [{required: true, message: "单品折扣不能为空", trigger: "blur"}],
        productGroup: [{required: true, message: "商品分组不能为空", trigger: "blur"}],
        isProductGroup: [{required: true, message: "商品分组不能为空", trigger: "blur"}],
        templateId: [{required: true, message: "请选择定价模板", trigger: "change"}],
        productTemplateType: [{required: true, message: "请选择商品类型", trigger: "change"}],
        productCategory: [{required: true, message: "请选择商品类目", trigger: "change"}],
        productWarehouse: [{required: true, message: "请选择商品选品范围", trigger: "change"}],
        // reviewStatus: [{required: true, message: "请选择商品品牌", trigger: "change"}],
      },
      productNumber: 0,//类目下商品数量
    }
  },
  created() {
    this.getBrandList() //获取商品品牌
    this.getPriceTemplateList() //获取智能定价模板
    this.getGoodsCategory() //获取商品类目

  },
  methods: {
    getCategoryData(list, n) {
      if (list.children && list.children.length > 0) {
        return this.getCategoryData(list.children, n + 1);
      } else {
        return n
      }
    },
    // 校验上架上限
    checkGroundLimit(rule, value, callback) {
      let value2 = this.form.pulishNumberByDay //每天上架数量
      if (value == 0) {
        callback(new Error("请重新选择计划执行日期，至少间隔1天!"));
      }
      value2 = Number(value2)
      value = Number(value)
      this.$Validate.isPositiveInteger(rule, value, callback)
      if (value < value2) {
        callback(new Error("上架上限数量不能小于每天上架数量！"));
      }
    },
    // 校验每天上架
    checkGroundNum(rule, value, callback) {
      let value2 = this.form.pulishUpperLimit //上架上限数量
      if (value && value2) {
        value2 = Number(value2)
        value = Number(value)
      }
      this.chooseGroundDate()
      // if (this.groundTime) {
      //   let nowDate = this.parseTime(new Date().getTime(), '{y}-{m}-{d}')
      //   let time1 = new Date(nowDate + ' ' + this.groundTime[0]).getTime();
      //   let time2 = new Date(nowDate + ' ' + this.groundTime[1]).getTime();
      //   let minute = (time2 - time1) / 5 / 1000 / 60 //计算分钟数：上架开始时间和结束时间的分钟数除以5
      //   if (value > minute) {
      //     callback(new Error("请增加上架时间或减少每天上架数量！"));
      //   }
      // }
      this.$Validate.isPositiveInteger(rule, value, callback)
    },
    // 校验最高价和最低价
    multipllCheck(rule, value, callback) {
      let value2 = this.form.priceFloor //最低价
      // if (value && value2) {
      value2 = Number(value2)
      value = Number(value)
      if (value < value2) {
        callback(new Error("最大金额不能小于最小金额！"));
      } else if (value == value2) {
        callback(new Error("最大金额不能等于最小金额！"));
      } else {
        this.$Validate.isInteger(rule, value2, callback)
      }
      // }
    },
    // 选择联盟折扣
    changeAfflicateDiscount(e) {
      this.form.afflicateDiscount = undefined
    },
    // 选择单品折扣
    changeProductDiscount(e) {
      this.form.productDiscount = undefined
    },
    // 选择商品分组
    changeProductGroup(e) {
      this.form.productGroup = undefined
    },
    // 获取智能定价模板
    getPriceTemplateList() {
      selectListBySellerId({sellerId: this.$store.getters.userId}).then(res => {
        this.priceTemplateList = res.data
      })
    },
    // 根据店铺ID获取品牌选择列表
    getBrandList() {
      getBrandListByStoreId({storeId: this.storeId}).then(res => {
        this.brandList = res.data.brandList
      })
    },
    // 确定提交
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.productNumber < this.form.pulishUpperLimit) { //如果商品数量小于上架上限
            // this.$alert("类目下商品数量不足，请调整上架上限数量！")
            this.$alert("类目下商品数量不足，请调整每天上架数量或缩短计划执行日期！", '提示')
            return
          }
          let nowDate = new Date().getTime();
          let startDate = new Date(this.groundDate[0]).getTime()
          // if (startDate < nowDate) {
          //   this.$alert("计划执行日期小于当前日期，请重新选择日期！", '提示')
          //   return
          // }
          this.$confirm('是否确定提交上架计划？', '提示').then(() => {
            this.form.productCategoryAncestors = ""
            for (let i = 0; i <= this.categoryIndex; i++) {
              this.form.productCategoryAncestors += this.categoryValueData['category' + i] + ','
            }
            if (this.isUseShareCode == '1') {
              this.form.id = undefined;
              this.form.storeId = this.storeId
              this.form.userId = this.userId
              this.form.storeUserName = this.storeUserName
            }
            let YYYYMMDDReg = new RegExp(/[\d]{4}[\/-]{1}[\d]{1,2}[\/-]{1}[\d]{1,2}/g);
            let YYYYMMDDHHmmssReg = new RegExp(/[\d]{4}[\/-]{1}[\d]{1,2}[\/-]{1}[\d]{1,2}\s[\d]{1,2}[:][\d]{1,2}[:][\d]{1,2}/g);
            // 如果是年月日日期格式
            if (this.groundDate[0].replace(YYYYMMDDReg, '') == '') {
              this.form.pulishBeginDay = this.groundDate[0] + ' 00:00:00'
              this.form.pulishEndDay = this.groundDate[1] + ' 23:59:59'
            } else {
              this.form.pulishBeginDay = this.groundDate[0]
              this.form.pulishEndDay = this.groundDate[1]
            }
            this.form.productCategoryAncestors = this.form.productCategoryAncestors.slice(0, this.form.productCategoryAncestors.length - 1)
            this.form.productBrand = this.form.productBrand ? this.form.productBrand.toString() : undefined
            if (this.form.id) {
              editPulishProject(this.form).then(res => {
                this.$message.success(res.msg)
                this.cancel()
              })
            } else {
              addPulishProductProject(this.form).then(res => {
                this.$message.success(res.msg)
                this.cancel()
              })
            }
          })

        }
      })
    },
    // 取消
    cancel() {
      this.$emit('close', false)
    },
    // 修改价格区间、品牌、选品范围、选品类型后更新商品数量
    changeProductNumber(e) {
      Object.keys(this.categoryValueData).forEach(key => {
        this.categoryValueData[key] = ''
      })
    },
    // 获取一级商品类目
    getGoodsCategory() {
      querySubCategoryListByStoreId({storeId: this.storeId}).then(response => {
        this.categoryList = response.data;
        if (this.configId) {
          this.getConfigDetail()
        } else {
          this.reset()
        }
      });
    },
    // 获取下级类目
    getSubcategoryList(e, type) {
      querySubordinateCategory({categoryId: e}).then(res => {
        this.form.productCategory = this.categoryValueData['category' + type]
        this.categoryIndex = type
        this.getCategoryProductNumber(e, type, res.data)
      })
    },
    // 获取类目下商品数量
    getCategoryProductNumber(e, type, list) {
      this.$modal.loading("正在获取商品数量，请稍候...");
      if (this.form.isBrand == '0') {
        this.form.productBrand = undefined
      }
      let data = {
        "priceFloor": this.form.priceFloor,
        "priceCeiling": this.form.priceCeiling,
        // "productBrand": productBrand ? typeof (productBrand) == "String" ? productBrand : productBrand.toString() : undefined,
        "productBrand": this.form.productBrand ? this.form.productBrand.toString() : undefined,
        "productWarehouse": this.form.productWarehouse,
        "productTemplateType": this.form.productTemplateType ? this.form.productTemplateType : undefined,
        "productCategory": this.form.productCategory,
        "storeId": this.storeId
      }
      queryStoreProductNumber(data).then(res => {
        // let data = JSON.parse(res.data)
        let data = res.data
        this.categoryValueData['list' + type] = list
        this.categoryValueData['number' + type] = data
        this.productNumber = data
        this.$modal.closeLoading()
        this.checkNum()
      })
    },
    // 校验数量规范
    checkNum() {
      if (this.productNumber < this.form.pulishUpperLimit) { //如果商品数量小于上架上限
        this.$message.error('类目下商品数量不足，请调整上架上限数量！')
        return
      }
      if (this.productNumber < this.form.pulishNumberByDay) { //如果商品数量小于每天上架数量

      }
    },
    // 选择执行计划日期 计算上架上限数量
    chooseGroundDate(e) {
      let days = this.$intervalDays(this.groundDate[0], this.groundDate[1]) //计算所选择日期间隔的天数
      if (days != undefined && this.form.pulishNumberByDay) {
        this.form.pulishUpperLimit = days * this.form.pulishNumberByDay
      }
    },
    // 选择上架时间
    chooseGroundTime(e) {
      if (e[0].split(':')[0] == '00') {
        this.$message.error('上架开始时间不能小于01：00！')
        this.groundTime = ["01:00", e[1]]
      } else {
        this.form.pulishBeginTime = e[0]
        this.form.pulishEndTime = e[1]
      }
    },
    // 获取上架配置详情
    getConfigDetail() {
      this.title = "修改上架配置"
      queryProjectById({id: this.configId}).then(res => {
        let data = res.data
        let dateList = []
        dateList.push(data.pulishBeginTime)
        dateList.push(data.pulishEndTime)
        for (let key in data) { //将所有字符转成字符串
          if (data[key] != null) {
            data[key] = '' + data[key]
          }
        }

        if (data.productCategoryAncestors) {
          let list = data.productCategoryAncestors.split(',');
          for (let i = 0; i < list.length; i++) {
            this.categoryValueData['category' + i] = Number(list[i])
            this.getSubcategoryList(list[i], i)
          }
        }
        this.form = data
        this.groundDate = [data.pulishBeginDay, data.pulishEndDay]
        if (this.form.productBrand) {
          this.form.productBrand = data.productBrand.split(',')
        }
        this.form.afflicateDiscount = Math.floor(data.afflicateDiscount)
        this.groundTime = dateList
      })
    },
    //   重置
    reset() {
      this.form = {
        projectName: undefined,
        pulishUpperLimit: undefined,
        pulishNumberByDay: undefined,
        priceCeiling: '99999',
        priceFloor: '1',
        productWarehouse: '1',
        isBrand: '0',
        productBrand: undefined,
        productTemplateType: undefined,
        productCategory: undefined,
        templateId: undefined,
        afflicateDiscount: undefined,
        allianceDiscount: undefined,
        productDiscount: undefined,
        productGroup: undefined,
        reviewStatus: '2',
        pulishBeginTime: this.groundTime[0],
        pulishEndTime: this.groundTime[1],
        storeId: this.storeId,
        storeUserName: this.storeUserName,
        isAfflicateDiscount: '0',
        isProductDiscount: '0',
        isProductGroup: '0',
        productCategoryAncestors: "",//类目id拼接
        userId: this.userId,
        pulishBeginDay: this.groundDate[0],
        pulishEndDay: this.groundDate[1]
      }
      this.resetForm("form");
    }
  }
}
</script>

<style scoped>

</style>
